let app = getApp();

Page({
  data: {
    consultants: [],
    filterData: null,
    url: app.globalData.url
  },

  onLoad(options) {
    const filterData = JSON.parse(decodeURIComponent(options.filter));
    if (filterData.region && filterData.region.includes('·无·无')) {
      filterData.region = filterData.region.replace('·无·无', '');
    }
    this.setData({ filterData });
    console.log('发送给后端的筛选条件:', JSON.stringify(filterData));
    this.fetchConsultants(filterData);
  },

  fetchConsultants(filterData) {
    wx.showLoading({ title: '加载中...' });
    const requestUrl = this.data.url + 'consultant/filter';

    wx.request({
      url: requestUrl,
      method: 'POST',
      data: filterData,
      header: { 'content-type': 'application/json' },
      success: (res) => {
        wx.hideLoading();
        console.log('后端响应状态码:', res.statusCode);
        console.log('后端返回数据:', res.data);

        if (res.statusCode === 200) {
          if (res.data.code === 200) {
            this.setData({ consultants: res.data.data || [] });
          } else {
            wx.showToast({
              title: `筛选失败: ${res.data.msg}`,
              icon: 'none',
              duration: 3000
            });
          }
        } else {
          wx.showToast({
            title: `服务器错误: ${res.statusCode}`,
            icon: 'none'
          });
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('网络请求失败:', err);
        wx.showToast({
          title: '网络连接失败，请检查网络',
          icon: 'none'
        });
      }
    });
  },

  goDetail(e) {
    wx.navigateTo({
      url: 'pages/consult/consultDetails/consultDetails?id='+e.currentTarget.dataset.id
    });
  },

  resetFilter() {
    wx.navigateBack();
  }
});